#!/usr/bin/env python3
"""
使用Selenium进行详细的HMI原型页面测试
自动启动浏览器并检查页面状态
"""

import time
import sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, WebDriverException
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service

def setup_driver():
    """设置Chrome浏览器驱动"""
    print("🔧 正在设置Chrome浏览器驱动...")
    
    chrome_options = Options()
    chrome_options.add_argument('--headless')  # 无头模式
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--window-size=1920,1080')
    chrome_options.add_argument('--disable-web-security')
    chrome_options.add_argument('--allow-running-insecure-content')
    
    try:
        # 使用webdriver-manager自动下载ChromeDriver
        service = Service(ChromeDriverManager().install())
        driver = webdriver.Chrome(service=service, options=chrome_options)
        print("✅ Chrome浏览器驱动设置成功")
        return driver
    except WebDriverException as e:
        print(f"❌ 无法启动Chrome浏览器: {e}")
        return None

def check_page_with_selenium(driver, url):
    """使用Selenium检查页面"""
    print(f"🌐 正在访问: {url}")
    
    try:
        # 访问页面
        driver.get(url)
        print("✅ 页面加载成功")
        
        # 等待页面完全加载
        time.sleep(5)
        
        # 检查页面标题
        title = driver.title
        print(f"📄 页面标题: {title}")
        
        # 检查页面源码
        page_source = driver.page_source
        print(f"📊 页面源码长度: {len(page_source)} 字符")
        
        # 检查根元素
        try:
            root_element = driver.find_element(By.ID, "root")
            root_html = root_element.get_attribute('innerHTML')
            if root_html.strip():
                print(f"🎯 根元素有内容，长度: {len(root_html)} 字符")
                print(f"🎯 根元素内容预览: {root_html[:200]}...")
                
                # 检查是否有React应用内容
                if "HMI系统启动中" in root_html:
                    print("✅ 发现React应用内容: HMI系统启动中")
                elif "TEST APP RENDERING" in root_html:
                    print("✅ 发现React应用内容: TEST APP RENDERING")
                elif "启动" in root_html or "登录" in root_html:
                    print("✅ 发现React应用内容: 启动/登录相关")
                else:
                    print("⚠️  根元素有内容但未识别为React应用")
            else:
                print("❌ 根元素为空")
        except Exception as e:
            print(f"❌ 无法获取根元素: {e}")
        
        # 检查控制台错误
        print("\n🔍 检查浏览器控制台日志...")
        logs = driver.get_log('browser')
        if logs:
            error_count = 0
            warning_count = 0
            for log in logs:
                if log['level'] == 'SEVERE':
                    print(f"  ❌ 严重错误: {log['message']}")
                    error_count += 1
                elif log['level'] == 'ERROR':
                    print(f"  ❌ 错误: {log['message']}")
                    error_count += 1
                elif log['level'] == 'WARNING':
                    print(f"  ⚠️  警告: {log['message']}")
                    warning_count += 1
                else:
                    print(f"  ℹ️  信息: {log['message']}")
            
            if error_count == 0:
                print("✅ 无严重错误")
            else:
                print(f"❌ 发现 {error_count} 个错误")
                
            if warning_count > 0:
                print(f"⚠️  发现 {warning_count} 个警告")
        else:
            print("✅ 无浏览器控制台日志")
        
        # 检查网络请求
        print("\n🌐 检查网络请求...")
        performance_logs = driver.get_log('performance')
        if performance_logs:
            failed_requests = 0
            for log in performance_logs:
                message = log.get('message', '')
                if 'Network.responseReceived' in message and 'status' in message:
                    if '"status":4' in message or '"status":5' in message:
                        failed_requests += 1
            
            if failed_requests == 0:
                print("✅ 无网络请求失败")
            else:
                print(f"❌ 发现 {failed_requests} 个网络请求失败")
        else:
            print("ℹ️  无性能日志")
        
        # 检查JavaScript执行
        print("\n🔧 检查JavaScript执行...")
        try:
            # 尝试执行简单的JavaScript
            result = driver.execute_script("return document.readyState;")
            print(f"✅ 页面状态: {result}")
            
            # 检查是否有React相关的全局变量
            react_check = driver.execute_script("return typeof React !== 'undefined';")
            print(f"✅ React全局变量: {'存在' if react_check else '不存在'}")
            
            # 检查是否有错误
            error_check = driver.execute_script("return window.onerror !== null;")
            print(f"✅ 错误处理: {'已设置' if error_check else '未设置'}")
            
        except Exception as e:
            print(f"❌ JavaScript执行检查失败: {e}")
        
        return True
        
    except TimeoutException:
        print("❌ 页面加载超时")
        return False
    except Exception as e:
        print(f"❌ 访问页面时出错: {e}")
        return False

def main():
    """主函数"""
    print("🚀 开始使用Selenium进行HMI原型页面测试...")
    
    # 设置浏览器驱动
    driver = setup_driver()
    if not driver:
        print("❌ 无法启动浏览器，测试终止")
        sys.exit(1)
    
    try:
        # 检查页面
        url = "http://localhost:5173"
        success = check_page_with_selenium(driver, url)
        
        if success:
            print("\n✅ Selenium测试完成")
        else:
            print("\n❌ Selenium测试失败")
            
    finally:
        driver.quit()
        print("🔚 浏览器已关闭")

if __name__ == "__main__":
    main()
